# -*- coding: utf-8 -*-  # 添加此行

'''
用户登录功能逻辑
'''

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database.database import get_db
from schemas.user import UserLogin, UserLoginResponse
from crud.user import login_user

async def UserLogin(user: UserLogin, db: Session = Depends(get_db)):
    """
    用户登录接口
    
    参数:
    - user: 用户登录信息 (用户名、密码)
    - db: 数据库会话
    
    返回:
    - 用户信息和登录成功消息
    """
    try:
        db_user = login_user(db, user)
        return UserLoginResponse(
            id=db_user.id,
            username=db_user.username,
            name=db_user.name,
            email=db_user.email,
            message="登录成功"
        )
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"登录失败: {str(e)}")